<?php

namespace ShowStop\UserBundle\Security\User\Provider;

use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use ShowStop\UserBundle\Entity\User;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use \BaseFacebook;
use \FacebookApiException;

class FacebookProvider implements UserProviderInterface
{
    /**
     * @var \Facebook
     */
    protected $facebook;
    protected $userManager;
    protected $validator;

    public function __construct(BaseFacebook $facebook, $userManager, $validator)
    {
        $this->facebook = $facebook;
        $this->userManager = $userManager;
        $this->validator = $validator;
    }

    public function supportsClass($class)
    {
        return $this->userManager->supportsClass($class);
    }

    public function findUserByFbId($fbId)
    {
    	$user =  $this->userManager
    	->createQuery("SELECT u FROM
    		         ShowStopUserBundle:User u
    		         WHERE u.facebookID = :fbID")
    	->setParameters(array('fbID' => $fbId ))
    	->getOneOrNullResult();
    	return $user;
    }

    public function loadUserByUsername($username)
    {
        $user = $this->findUserByFbId($username);
		
        try {
            $fbdata = $this->facebook->api('/me');
        } catch (FacebookApiException $e) {
            $fbdata = null;
        }
        
        if (!empty($fbdata)) {
            if ( empty($user) ) {
                $user = new User();
                $user->setPassword('');
                $query = $this->userManager->createQuery( "SELECT r FROM ShowStopUserBundle:Role r WHERE r.name = 'ROLE_USER'" );
    			$role = $query->getSingleResult();
    			$user->getUserRoles()->add( $role );
    		
            }
			
            
            // TODO use http://developers.facebook.com/docs/api/realtime
            $user->setFBData($fbdata);

            if (count($this->validator->validate($user, 'Facebook'))) {
                // TODO: the user was found obviously, but doesnt match our expectations, do something smart
                throw new UsernameNotFoundException('The facebook user could not be stored');
            }
            $this->userManager->persist( $user );
            $this->userManager->flush();
        }

        if (empty($user)) {
            throw new UsernameNotFoundException('The user is not authenticated on facebook');
        }

        return $user;
    }

    public function refreshUser(UserInterface $user)
    {
        if (!$this->supportsClass(get_class($user)) || !$user->getFacebookId()) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
        }

        return $this->loadUserByUsername( $user->getFacebookId() );
    }
}

?>